package cn.zysheep.controller;

import cn.zysheep.feign.clients.UserClient;
import cn.zysheep.feign.pojo.User;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/17
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    UserClient userClient;
    /**
     * 注意 blockHandler 函数会在原方法被限流/降级/系统保护的时候调用，
     * 而 fallback 函数会针对所有类型的异常。请注意 blockHandler 和 fallback 函数的形式要求
     *
     * @param id
     * @return
     */
    @GetMapping("/query/{id}")
    @SentinelResource(value = "queryUserById", blockHandler = "productBlockHandler", fallback = "productFallBack")
    //@SentinelResource(value = "queryUserById")
    public ResponseEntity<?> queryUserById(@PathVariable("id") Long id) {
        HashMap forObject = restTemplate.getForObject("http://user-service/user/" + id, HashMap.class);

        return ResponseEntity.ok(forObject);
    }

    //Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public ResponseEntity<?> productBlockHandler(Long id, BlockException ex) {
        // 在这里做一些日志处理.
        ex.printStackTrace();
        return ResponseEntity.ok("降级方法");
    }

    // 异常回调 Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public ResponseEntity<?> productFallBack( Long id) {
        return ResponseEntity.ok("异常回调");
    }


    @GetMapping("/queryUser/{id}")
    public ResponseEntity<?> queryUser(@PathVariable("id") Long id) {
        User user = userClient.queryById(id);
        return ResponseEntity.ok(user);
    }
}
